package com.qida.clm.core.utils;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;


/**
 * Created by Admin on 2015/8/9.
 */
public final class ThreadUtils {

    public static String test ="";
    private static Handler sMainHandler = new Handler(Looper.getMainLooper());
    private static ExecutorService sExecutorService = Executors.newSingleThreadExecutor();

    public static void postDelayed(Runnable runnable,long delayed){
        if(runnable != null){
            sMainHandler.postDelayed(runnable,delayed);
        }
    }

    public static void post(Runnable runnable){
        if(runnable != null){
            sMainHandler.post(runnable);
        }
    }

    public static void runMainThread(Runnable runnable){
        if(runnable != null){
            if(checkMainThread()){
                runnable.run();
            } else {
                sMainHandler.post(runnable);
            }
        }
    }

    /**
     * post in ui thread,block wait result
     * @param task
     * @param <T>
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static <T> T executeMainThread(FutureTask<T> task)throws RuntimeException{
        try {
            if(task != null){
                if(checkMainThread()){
                    task.run();
                } else {
                    sMainHandler.post(task);
                }
                return task.get();
            } else {
                throwsException("FutureTask is null");
            }
        }catch (ExecutionException e){
            throw new RuntimeException(e);
        } catch (InterruptedException e){
            throw new RuntimeException(e);
        }
        return null;
    }
    
    public static void executeSlaveThread(Runnable runnable) {
    	if (runnable != null) {
            sExecutorService.execute(runnable);
		}
    }

    public static <T> T executeMainThread(Callable<T> callable)throws RuntimeException{
        if(callable == null){
            throwsException("Callable is null");
        }
        return executeMainThread(new FutureTask<T>(callable));
    }

    private static void throwsException(String message){
        throw new NullPointerException(message);
    }

    /**
     * 检查是否是主线程
     * @return
     */
    private static boolean checkMainThread(){
        return Looper.getMainLooper() == Looper.myLooper();
    }
    
}